#include "settingwidget.h"
#include <QGuiApplication>
#include <QLabel>
#include <QLine>
#include <QMouseEvent>
#include <QPainter>
#include <QTableWidget>
#include <QVBoxLayout>
#include "settingWidget/about/aboutsoftware.h"
#include "settingWidget/audioWidget/audiowidget.h"
#include "settingWidget/commonSettingWidget/commonsettting.h"
#include "settingWidget/videoWidget/videowidget.h"
#include "utils/GenericaTask.h"
#include "utils/util.h"
#include <settingWidget/NetWorkDetection/netdetectionwidget.h>
QString styleSheetTempalte = "QPushButton { border: none; border-image: "
                             "url(%1) 0 0 0 0 stretch stretch;}";
settingWidget::settingWidget(QWidget *parent)
    : QWidget{parent}
    , qHboxLayout(new QHBoxLayout())
    , btnClose(new QPushButton())
    , btnSetting(new QPushButton())
    , btnCamera(new QPushButton())
    , btnVoice(new QPushButton())
    , btnNet(new QPushButton())
    , btnKeyBoard(new QPushButton())
    , btnAbout(new QPushButton())
    , stackWidget(new QStackedWidget(this))
    , btnGroup(new QButtonGroup(this))
    , preClickedButtonID(1)
{
    // this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowMinMaxButtonsHint);
    this->setStyleSheet("background-color: white;");
    QVBoxLayout *mainVBoxLayout = new QVBoxLayout(this);
    mainVBoxLayout->setObjectName("mainVBoxLayout");
    //设置页边距
    mainVBoxLayout->setContentsMargins(5, 5, 5, 5);
    //设置mainVBoxLayout组件内的空间的间距为0
    mainVBoxLayout->setSpacing(2);

    QLabel *titleLabel = new QLabel();
    setLable(titleLabel, "titleLabel", "设置", "Microsoft YaHei", 10);
    titleLabel->setMinimumHeight(30);
    qHboxLayout->addWidget(titleLabel);

    setPushBtn(btnClose,
               "btnClose",
               QSize(25, 30),
               "",
               "QPushButton{border:none}",
               true,
               ":/resources/close1.png");
    qHboxLayout->addWidget(btnClose);

    btnClose->installEventFilter(this);
    mainVBoxLayout->addLayout(qHboxLayout);

    //添加一个水平布局，这个布局里面需要放置左侧的按钮和一个stackWidget
    QHBoxLayout *HboxLayout3 = new QHBoxLayout();
    HboxLayout3->setObjectName("HboxLayout3");
    HboxLayout3->setSpacing(2); //这是这个布局内组件的间距
    HboxLayout3->setContentsMargins(0, 0, 0, 0);

    //添加一个垂直布局

    QVBoxLayout *btnVboxLayout = new QVBoxLayout();
    btnVboxLayout->setSpacing(0);
    btnVboxLayout->setContentsMargins(0, 0, 0, 0);
    //添加第一个按钮
    setPushBtn(btnSetting,
               "btnSetting",
               QSize(170, 43),
               "",
               "QPushButton { border: none; border-image: url(:/resources/commonSetting3.png) 0 0 "
               "0 0 stretch stretch; }",
               false,
               "");
    buttonIconMap.insert(btnSetting,
                         QPair<QString, QString>(":/resources/commonSetting2.png",
                                                 ":/resources/commonSetting1.png"));
    btnSetting->installEventFilter(this);
    //将第一个按钮设置为点击状态
    activeBtn = btnSetting;
    btnVboxLayout->addWidget(btnSetting);

    //添加第二个按钮
    setPushBtn(btnCamera,
               "btnCamera",
               QSize(170, 43),
               "",
               "QPushButton { border: none; border-image: url(:/resources/cam1.png) 0 0 "
               "0 0 stretch stretch; }",
               false,
               "");
    buttonIconMap.insert(btnCamera,
                         QPair<QString, QString>(":/resources/cam2.png", ":/resources/cam1.png"));
    btnCamera->installEventFilter(this);
    btnVboxLayout->addWidget(btnCamera);

    //添加第三个按钮
    setPushBtn(btnVoice,
               "btnVoice",
               QSize(170, 43),
               "",
               "QPushButton { border: none; border-image: url(:/resources/voice1.png) 0 0 "
               "0 0 stretch stretch; }",
               false,
               "");
    buttonIconMap.insert(btnVoice,
                         QPair<QString, QString>(":/resources/voice2.png",
                                                 ":/resources/voice1.png"));
    btnVoice->installEventFilter(this);
    btnVboxLayout->addWidget(btnVoice);

    //添加第四个按钮
    setPushBtn(btnNet,
               "btnNet",
               QSize(170, 43),
               "",
               "QPushButton { border: none; border-image: url(:/resources/net1.png) 0 0 "
               "0 0 stretch stretch; }",
               false,
               "");
    buttonIconMap.insert(btnNet,
                         QPair<QString, QString>(":/resources/net2.png", ":/resources/net1.png"));
    btnNet->installEventFilter(this);
    btnVboxLayout->addWidget(btnNet);

    //添加第五个按钮
    setPushBtn(btnKeyBoard,
               "btnKeyBoard",
               QSize(170, 43),
               "",
               "QPushButton { border: none; border-image: url(:/resources/keyboard1.png) 0 0 0 0 "
               "stretch stretch;}",
               false,
               "");
    buttonIconMap.insert(btnKeyBoard,
                         QPair<QString, QString>(":/resources/keyboard2.png",
                                                 ":/resources/keyboard1.png"));
    btnKeyBoard->installEventFilter(this);
    btnVboxLayout->addWidget(btnKeyBoard);

    setPushBtn(btnAbout,
               "btnAbout",
               QSize(170, 43),
               "",
               "QPushButton { border: none; border-image: url(:/resources/about1.png) 0 0 0 0 "
               "stretch stretch;}",
               false,
               "");
    buttonIconMap.insert(btnAbout,
                         QPair<QString, QString>(":/resources/about2.png",
                                                 ":/resources/about1.png"));
    btnAbout->installEventFilter(this);
    btnVboxLayout->addWidget(btnAbout);

    QLabel *spaceLabel = new QLabel();
    spaceLabel->setMinimumSize(QSize(170, 340));
    spaceLabel->setMaximumSize(QSize(170, 340));
    btnVboxLayout->addWidget(spaceLabel);

    HboxLayout3->addLayout(btnVboxLayout);

    //初始化statckWidget
    initStackWidget();

    HboxLayout3->addWidget(stackWidget);
    mainVBoxLayout->addLayout(HboxLayout3);

    createQButtonGroup();
    connect(btnGroup, &QButtonGroup::idClicked, this, &settingWidget::onButtonClicked);
    connect(btnClose, &QPushButton::clicked, this, [=]() {
        close();
        emit clearSetting();
    });

    this->setWindowFlags(Qt::FramelessWindowHint | Qt::Widget);
}

void settingWidget::centerWindow()
{
    //1、需要获得指针的位置
    QPoint cursorPos = QCursor::pos();
    //2、获取指针所在的屏幕
    QScreen *screen = QGuiApplication::screenAt(cursorPos);

    if (screen) {
        //3、获得指针所在的屏幕的矩形
        QRect rect = screen->geometry();

        int x = (rect.width() - width()) / 2;
        int y = (rect.height() - height()) / 2;
        move(x, y);
    }
}

void settingWidget::setTableWidgetItem(QTableWidgetItem *item, const QString IconURL)
{
    QIcon icon(IconURL);
    item->setIcon(icon);
    Qt::ItemFlags flags = item->flags();
    flags &= ~Qt::ItemIsEditable; //这是不可编辑
    item->setFlags(flags);
}

/**
 * @brief settingWidget::createQButtonGroup  这个函数是用来管理一组的按钮的，我们将一些按钮添加到QButtonGroup，然后通过idClicked信号，可以知道
 * 当前哪个按钮被点击了
 */
void settingWidget::createQButtonGroup()
{
    btnGroup->setExclusive(true);
    btnGroup->addButton(btnSetting, 1);
    btnGroup->addButton(btnCamera, 2);
    btnGroup->addButton(btnVoice, 3);
    btnGroup->addButton(btnNet, 4);
    btnGroup->addButton(btnKeyBoard, 5);
    btnGroup->addButton(btnAbout, 6);
}

void settingWidget::initStackWidget()
{
    //设置stackWidget
    stackWidget->setObjectName("stackWidget");

    //创建第一个页面
    commonSettting *comSettingWidget = new commonSettting();
    comSettingWidget->setObjectName("comSettingWidget");
    stackWidget->addWidget(comSettingWidget);

    //第二个页面
    video = new videoWidget();
    video->setObjectName("video");
    stackWidget->addWidget(video);

    //第三个页面
    audioWidget *audiowidget = new audioWidget();
    audiowidget->setObjectName("audiowidget");
    stackWidget->addWidget(audiowidget);
    connect(this, &settingWidget::stopSpeaker, audiowidget, &audioWidget::stopSpeaker);

    //第4和5用第一个先占住
    network1 = new NetDetectionWidget();
    network1->setObjectName("network");
    stackWidget->addWidget(network1);
    connect(this, &settingWidget::stopCheck, network1, &NetDetectionWidget::onStopCheck);
    //连接检测完成信号
    connect(network1,
            &NetDetectionWidget::checkNetworkFinished,
            this,
            &settingWidget::oncheckNetworkFinished);

    commonSettting *comSettingWidget2 = new commonSettting();
    stackWidget->addWidget(comSettingWidget2);

    aboutSoftWare *abount = new aboutSoftWare();
    abount->setObjectName("abount");
    stackWidget->addWidget(abount);

    netfinshed = new NetFinishedWidget(this);
    netfinshed->setObjectName("netfinshed");
    stackWidget->addWidget(netfinshed);
    connect(netfinshed,
            &NetFinishedWidget::checkAgainSignal,
            this,
            &settingWidget::onCheckNetworkAgain);
}

void settingWidget::changeBtnIcon(int preIndex, int currentIndex)
{
    switch (preIndex) {
    case 1:
        btnSetting->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/commonSetting1.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 2:
        btnCamera->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/cam1.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 3:
        btnVoice->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/voice1.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 4:
        btnNet->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/net1.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 5:
        btnKeyBoard->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/keyboard1.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 6:
        btnAbout->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/about1.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    default:
        break;
    }

    switch (currentIndex) {
    case 1:
        btnSetting->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/commonSetting3.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 2:
        btnCamera->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/cam3.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 3:
        btnVoice->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/voice3.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 4:
        btnNet->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/net3.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 5:
        btnKeyBoard->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/keyboard3.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    case 6:
        btnAbout->setStyleSheet(
            "QPushButton { border: none; border-image: url(:/resources/about3.png) 0 0 "
            "0 0 stretch stretch; }");
        break;
    default:
        break;
    }
}

bool settingWidget::eventFilter(QObject *watch, QEvent *event)
{
    QAbstractButton *button = qobject_cast<QAbstractButton *>(watch);
    if (button && buttonIconMap.contains(button)) {
        // qDebug() << "发出了事件";
        //然后我需要判断按钮是否处于激活的状态，即是蓝色的背景的状态
        if (button != activeBtn) {
            const QPair<QString, QString> &icons = buttonIconMap.value(button);
            if (event->type() == QEvent::Enter) {
                QString styleSheetString = styleSheetTempalte.arg(icons.first);
                button->setStyleSheet(styleSheetString);
            } else if (event->type() == QEvent::Leave) {
                QString styleSheetString = styleSheetTempalte.arg(icons.second);
                button->setStyleSheet(styleSheetString);
            }
        }
    } else if (button && button == btnClose) {
        if (event->type() == QEvent::Enter) {
            QIcon icon(":/resources/close2.png");
            button->setIcon(icon);
            button->setIconSize(button->size());
        } else if (event->type() == QEvent::Leave) {
            QIcon icon(":/resources/close1.png");
            button->setIcon(icon);
            button->setIconSize(button->size());
        }
    }
    return QObject::eventFilter(watch, event);
}

void settingWidget::startCameraInThread()
{
    qDebug() << "摄像头正在打开";
    video->showVideo();
}

void settingWidget::stopCameraInThread()
{
    qDebug() << "摄像头正在关闭";
    video->stopVideo();
}

void settingWidget::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    centerWindow();
}

void settingWidget::onButtonClicked(int id)
{
    if (id != preClickedButtonID) {
        // qDebug() << "onButtonClicked";
        stackWidget->setCurrentIndex(id - 1);
        if (id == 2) {
            globalThreadPool->start(
                new GenericTask(std::bind(&settingWidget::startCameraInThread, this)));
        } else if (id != 2) {
            if (video->cameraStatus()) {
                globalThreadPool->start(
                    new GenericTask(std::bind(&settingWidget::stopCameraInThread, this)));
            }
        }
        changeBtnIcon(preClickedButtonID, id);
        if (preClickedButtonID == 3) {
            emit stopSpeaker();
        } else if (preClickedButtonID == 4)
            emit stopCheck();
    }
    activeBtn = btnGroup->button(id);
    preClickedButtonID = id;
}

void settingWidget::oncheckNetworkFinished(bool a, bool b, bool c, qint64 d, qint64 e)
{
    if (netfinshed)
        netfinshed->setNetworkStatusDisplay(a, b, c, d, e);
    else {
        qDebug() << "netfinshed is nullptr";
        return;
    }
    stackWidget->setCurrentIndex(6);
}

void settingWidget::onCheckNetworkAgain()
{
    qDebug() << "onCheckNetworkAgain";
    stackWidget->setCurrentIndex(3);
    network1->onbtnDetectionClick();
}

void settingWidget::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    QPen pen(QColor(128, 128, 128));
    pen.setWidth(1); // 设置你需要的线条宽度
    painter.setPen(pen);

    QLine verticalLine(QPoint(177, 37), QPoint(177, 700));
    QLine horizontalLine(QPoint(0, 37), QPoint(800, 37));
    painter.drawLine(horizontalLine);
    painter.drawLine(verticalLine);

    //获取绘制的区域
    QRect rect = this->rect();
    painter.drawRect(rect);
}

void settingWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = true;
        m_offset = event->globalPosition().toPoint() - frameGeometry().topLeft();
        event->accept();
    }
}

void settingWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging) {
        move(QPoint(static_cast<int>(event->globalPosition().x() - m_offset.x()),
                    static_cast<int>(event->globalPosition().y() - m_offset.y())));
        event->accept();
    }
}

void settingWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragging = false;
        event->accept();
    }
}
